//
//  TripArrangeVC.swift
//  ImGuider X
//
//  Created by 王鹏宇 on 9/27/18.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit

let collectionH = kScreenHeight - kNavigationBarHeight - kBottomHeight

class TripArrangeVC: BaseVC,DayHeaderViewDelegate {
    
    @IBOutlet weak var toTopNavH: NSLayoutConstraint!
    
    var tripImageView: UIImageView!
    var tripNameLabel: UILabel!
    var dateLabel: UILabel!
    
    var collectionView: UICollectionView!
    
    @IBOutlet weak var tableView: UITableView!
    var  selectView: UIView!
    var  selectImageView = UIImageView()
    var  selectDateLabel : UILabel!
    
    var outSelectDay:Int = 0
    
    var viewmodel:TripArrangeViewModel = TripArrangeViewModel()
    var isDrag : Bool = true
    var whiteBg : UIView!
    var shotImageView : UIImageView = UIImageView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupData()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        DispatchQueue.main.after(1) {
            self.foldViewDisappear()
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        WPY_AVPlayer.playManager.stop()
    }
    
    private func setupUI(){
        
        
        self.tableView.backgroundColor = kThemeBgColor
        
        self.tableView.register(UINib(nibName: "ArrangeCell", bundle: nil), forCellReuseIdentifier: "ArrangeCell")
        
        self.tableView.register(DayHeaderView.self, forHeaderFooterViewReuseIdentifier: "DayHeaderView")
        
        //tableView 自适应高度
        self.tableView.rowHeight = UITableView.automaticDimension
        self.tableView.estimatedRowHeight = 2
        self.tableView.estimatedSectionFooterHeight = 2
        self.tableView.estimatedSectionFooterHeight = 2
        self.closeAutomaticallyInsets(scrollview: self.tableView)
        
        self.toTopNavH.constant = CGFloat(kNavigationBarHeight)
        setupHeaderView()
    }
    
    func setupHeaderView(){
        
        let height = kScreenWidth / 16 * 9
        
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: height))
        
        tripImageView = UIImageView(frame: view.frame)
        tripImageView.contentMode = .scaleAspectFill
        tripImageView.clipsToBounds = true
        view.addSubview(tripImageView)
        
        let maskView = UIView(frame:tripImageView.bounds)
        maskView.backgroundColor = kTitleColor.withAlphaComponent(0.2)
        tripImageView.addSubview(maskView)
        dateLabel = UILabel()
        view.addSubview(dateLabel)
        dateLabel.font = UIFont.systemFont(ofSize: 12)
        dateLabel.textColor = UIColor.white
        dateLabel.snp.makeConstraints { (make) in
            make.top.equalTo(view.snp.top).offset(20)
            make.leading.equalTo(view.snp.leading).offset(20)
            make.trailing.equalTo(view.snp.trailing).offset(-20)
        }
        
        tripNameLabel = UILabel()
        view.addSubview(tripNameLabel)
        tripNameLabel.textColor = UIColor.white
        tripNameLabel.font = UIFont.systemFont(ofSize: 20)
        tripNameLabel.numberOfLines = 2
        tripNameLabel.snp.makeConstraints { (make) in
            make.leading.equalTo(view.snp.leading).offset(20)
            make.trailing.equalTo(view.snp.trailing).offset(-20)
            make.bottom.equalTo(view.snp.bottom).offset(-25)
        }
        
        self.tableView.tableHeaderView = view
        
        let  layout =  UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 83, height: 60)
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        collectionView = UICollectionView(frame: CGRect(x: 0, y: height + kNavigationBarHeight + 56, width: 83, height: collectionH), collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        self.collectionView.backgroundColor = UIColor.clear
        self.view.addSubview(collectionView)
        self.collectionView.register(UINib(nibName: "DateCell", bundle: nil), forCellWithReuseIdentifier: "DateCell")
        
        
        selectView = UIView(frame: CGRect(x: 0, y: height + kNavigationBarHeight, width: 88, height: 63))
        self.view.insertSubview(selectView, aboveSubview: collectionView)
        selectView.addSubview(selectImageView)
        selectImageView.frame = selectView.bounds
//        selectView.backgroundColor =  UIColor.hexStringToColor(hexString: "#E2E2E2")
        
        selectDateLabel = UILabel()
        selectDateLabel.textColor = UIColor.white
        selectDateLabel.textAlignment = .center
        selectDateLabel.font = UIFont.systemFont(ofSize: 24)
        selectDateLabel.text = "D1"
        selectView.addSubview(selectDateLabel)
        selectDateLabel.snp.makeConstraints { (make) in
            make.top.bottom.left.right.equalToSuperview()
        }
        
//        let gradientColors = [UIColor(red: 210/255.0, green: 210/255.0, blue: 210/255.0, alpha: 1.0),UIColor(red: 118/255.0, green: 118/255.0, blue: 118/255.0, alpha: 1.0)]
//
//        let layer = CAGradientLayer.gradientLayer(colors: gradientColors, position: .leftToRight, frame: selectView.bounds)
        
        if let image = UIImage(named: "foldOff"){
            selectImageView.image = image
        }
        
//        selectView.layer.insertSublayer(layer, at: 0)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(dateAction(sender:)))
        
        self.selectView.addGestureRecognizer(tap)
        
//        self.shotImageView.contentMode = .scaleAspectFill
        self.shotImageView.clipsToBounds = true
        self.view.addSubview(self.shotImageView)
//        whiteBg = UIView(frame: CGRect(x: 0, y: height, width: kScreenWidth, height: 60))
//        whiteBg.backgroundColor = UIColor.white
//
//        self.tableView.addSubview(whiteBg)
        
    }
    
    private func setupData() {
        
        self.title = LocalizedString("trip_detail")
        
        viewmodel.currentDay = outSelectDay
        
        viewmodel.reloadDay = {
            
            [weak self] in
            guard let `self` = self else { return }
            self.tableView.reloadData()
            
            self.tableView.layoutIfNeeded()
            
            self.tableView.setContentOffset(CGPoint.zero, animated: true)
            
        }
        
        self.tripNameLabel.text = viewmodel.trip?.planName
        
        
        var plandate = viewmodel.trip?.planDate("yyyy/MM/dd")
        
        if AppManager.share.language == .english {
            
            plandate = viewmodel.trip?.planDate("dd MMM yyyy")
        }
        
        self.dateLabel.text = plandate
        self.tripImageView.setImage(string: viewmodel.trip?.pictureArray?.first, placeholder: UIImage(named:"placeholder_rec")!)
    }
    
    
    @objc func dateAction(sender : UITapGestureRecognizer){
        
        if self.collectionView.isHidden {
            self.foldViewAppear()
        }else{
            self.foldViewDisappear()
            
        }
    }
}

extension TripArrangeVC: UITableViewDelegate,UITableViewDataSource {
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        if scrollView.isKind(of: UITableView.self) {
            self.isDrag = true
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if scrollView.isKind(of: UITableView.self) {
            
            let standarOffsetY : CGFloat = CGFloat(kScreenWidth / 16 * 9)
            
            
            let offsetY = scrollView.contentOffset.y
            
            
            if offsetY > standarOffsetY {
                
                selectView.frame = CGRect(x: 0, y:kNavigationBarHeight, width: 88, height:63)
                collectionView.frame = CGRect(x: 0, y:kNavigationBarHeight + 56, width: 83, height:collectionH)
                if !shotImageView.isHidden {
                    self.shotImageView.frame = CGRect(x: 0, y:kNavigationBarHeight + 56, width: 83, height:Int(self.shotImageView.frame.size.height))
                }
                
            }else {
                
                selectView.frame = CGRect(x: 0, y:Int(standarOffsetY - offsetY) + kNavigationBarHeight, width: 83, height:63)
                collectionView.frame = CGRect(x: 0, y: Int(standarOffsetY - offsetY) + kNavigationBarHeight + 56 , width: 83, height: collectionH)
                if !shotImageView.isHidden{
                    var rect = self.shotImageView.frame
                    rect.origin.y = standarOffsetY - offsetY
                    self.shotImageView.frame = rect
                }
            }
            
            
            
            if  let  cell = self.tableView.visibleCells.first, self.isDrag == true {
                
                let indexPath = self.tableView.indexPath(for: cell)
                self.selectDateLabel.text = "D\((indexPath?.section ?? 0) + 1)"
                
            }
            
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return self.viewmodel.days?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if let day = viewmodel.days?[section] {
            
            let count = day.calendars?.count ?? 0
            
            if day.hotel != nil {
                
                return count + 1
            }
            
            return count
        }
        return  0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "ArrangeCell") as? ArrangeCell else  {
            return ArrangeCell()
        }
        
        if let day = viewmodel.days?[indexPath.section] {
            
            if day.calendars?.count == indexPath.row {
                
                cell.calendar = day.hotel
            } else {
                
                cell.calendar = day.calendars?[indexPath.row]
            }
            
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "DayHeaderView") as! DayHeaderView

        let day = viewmodel.days?[section]
        headerView.delegate = self
        headerView.day = day
        headerView.dayLabel.text = "D\(section + 1)"
        
        if day?.featureCalendar?.count ?? 0 > 0 {
            
            headerView.mapBtn.isHidden = false
        } else {
            
            headerView.mapBtn.isHidden = true
        }
        
        return headerView
    }
    
    //    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    //
    //        if let headerView = view as? DayHeaderView{
    //            headerView.backgroundView?.backgroundColor = UIColor.clear
    //        }
    //    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        //        if section == 0 {
        //            return 40
        //        }
        //        return 0.0001
        
        return 60
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        guard let day = viewmodel.days?[indexPath.section] else {return}
        
        var calendar:Calendar? = nil
        
        if day.calendars?.count == indexPath.row {
            
            calendar = day.hotel
        } else {
            
            calendar = day.calendars?[indexPath.row]
        }
        
        if calendar?.planType == .flight {
            
            let airVC = AirplaneDetailVC()
            airVC.viewmodel.calender = calendar
            self.navigationController?.pushViewController(airVC, animated: true)
            
            return
        }
        
        let otherVC = OtherDetailVC()
        otherVC.viewmodel.calendar = calendar
        
        self.navigationController?.pushViewController(otherVC, animated: true)
    }
    
    
    func foldViewAppear(){
        var  rect = self.collectionView.frame
         rect.size.height = 0
        self.shotImageView.frame = rect
        self.shotImageView.isHidden = false
        if let image = UIImage(named: "foldOff") {
            selectImageView.image = image
        }
        rect.size.height = self.collectionView.bounds.height
        
        UIView.animate(withDuration: 0.5, animations: {
           
            self.shotImageView.frame = rect
        }) { (finished) in
            
            self.shotImageView.isHidden = true
            self.collectionView.isHidden = false
        }
    }
    
    func foldViewDisappear(){
        
        var rect = self.collectionView.frame
        self.shotImageView.frame = rect
        self.shotImageView.image = self.collectionView.screenShot()
        self.shotImageView.isHidden = false
         self.collectionView.isHidden = true
        rect.size.height = 0
        UIView.animate(withDuration: 0.5, animations: {
            self.shotImageView.frame = rect
        }) { (finished) in
            if let image = UIImage(named: "foldOn") {
                self.selectImageView.image = image
            }
            self.shotImageView.isHidden = true
        }
    }
    
    func goMapVC(day: Day?) {
        
        let mapVC = TripMapVC()
        mapVC.viewmodel.day = day
        
        self.navigationController?.pushViewController(mapVC, animated: true)
    }
}

extension TripArrangeVC: UICollectionViewDelegate,UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        print(viewmodel.days?.count ?? 0)
        
        return viewmodel.days?.count ?? 0
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DateCell", for: indexPath) as! DateCell
        
        cell.day = viewmodel.days?[indexPath.row]
        
        cell.normalDateLabel.text = "D\(indexPath.row + 1)"
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        //        if viewmodel.currentDay == indexPath.row {
        //            return
        //        }
        //
        //        if let cell = collectionView .cellForItem(at: IndexPath(item: viewmodel.currentDay, section: 0)) as? DateCell {
        //
        //            cell.isSelect = false
        //        }
        //
        //        guard let selectCell = collectionView.cellForItem(at: indexPath) as? DateCell else { return }
        //
        //        selectCell.isSelect = true
        //
        //        viewmodel.currentDay = indexPath.row
        
        if let cout = self.viewmodel.days?.count,indexPath.row < cout {
           
            if let day = self.viewmodel.days?[indexPath.row],(day.calendars?.count ?? 0) > 0{
                
                let path = IndexPath(row: 0, section: indexPath.row)
                self.tableView.scrollToRow(at: path, at: UITableView.ScrollPosition.top, animated: true)
            }
           
           
            
            self.isDrag = false
            self.foldViewDisappear()
            self.selectDateLabel.text = "D\(indexPath.row + 1)"
        }
        
    }
}


